﻿using CefSharp;
using CefSharp.WinForms;
using Ledict.ConditionExtract.Authority;
using Ledict.ConditionExtract.Common;
using Ledict.Utility.Frm;
using System;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace Ledict.ConditionExtract
{
    public class Gvar
    {
        public static AT_User uo = null;
    }

    internal static class Program
    {
        /// <summary>
        ///应用程序的主入口点。
        /// </summary>
        [STAThread]
        private static void Main()
        {
            //string ipnut = "重庆中科建设有限公司确认劳动关系纠纷";
            //Match res = System.Text.RegularExpressions.Regex.Match(ipnut, @"(?:确认|恢复)?(?:不存在)?劳动关系\w*?(?!\w*?管辖权异议)",System.Text.RegularExpressions.RegexOptions.Singleline);
            //string res1= res.Value;
            // 创建并给 List 赋值
            //List<Person> list = new List<Person>();
            //list.Add(new Person { name = "李四", password = "123456", age = 20 });
            //list.Add(new Person { name = "张三", password = "123456", age = 18 });
            //list.Add(new Person { name = "王五", password = "123456", age = 22 });
            //list.Add(new Person { name = "张三", password = "123456", age = 18 });
            //// 去重操作
            //List<Person> var= list.GroupBy(x => x.name).Select(x => x.First()).ToList();

            //IFreeSql fsql= SqlManage.sqlServer;
            //DataTable st = fsql.Select<SYS_CaseCause>().Where(x => x.CC_ID == "1655").ToDataTable();
            //CaseCauseDAL cd = new CaseCauseDAL();
            //cd.ShowData();

            //WorkThread_Public work = new WorkThread_Public();
            //work.AddMatch_virtual("SCC2103161418460001", "单一");
            //work.AddMatch_virtual("MCC2103161418460001", "组合");
            //string res = new NodeTree().GetFTContent("6376046");
            //string AllParentName = "行政执法,食品安全,违法行为,销售无包装的直接入口食品时，未使用无毒、清洁的容器、售货工具和设备";
            //AllParentName = AllParentName.Replace("行政执法,", "");
            //AllParentName = AllParentName.Substring(0, AllParentName.IndexOf(',')).ToString();

            #region 对SYS_Express_Word表中的数据进行处理，处理逻辑，首先获取SYS_Express_Word_Process表中打对勾的数据，然后根据ewid获取表述表的文本内容，如果不一致则修改内容，否则添加
            // Express_WordDAL wordbll = new Express_WordDAL();

            #region 将打对勾的ccid中cc_isshowExpress为0的民事的数据修改
            //DataTable dt1 = wordbll.GetExpressWordData4();
            //if (dt1 != null && dt1.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt1.Rows)
            //    {
            //        string[] str = dr["AllParentId"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            //        if (str.Length > 0)
            //        {
            //            foreach (var item in str)
            //            {
            //                bool res = wordbll.UpdateCC_IsShowExpress(item, 1);
            //            }
            //        }
            //    }
            //} 
            #endregion

            //var model = new SYS_Express_Word();
            //DataTable dt = wordbll.GetExpressWordData3();
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {
            //        string ewID = dr["EW_ID"].ToString();
            //        string ewContent = dr["EW_Content"].ToString();
            //        string res = wordbll.Exists_WordProcess(ewID);
            //        if (!string.IsNullOrEmpty(res))
            //        {
            //            if (res != ewContent)
            //            {
            //                wordbll.UpdateWordContent(ewID, ewContent);
            //            }
            //        }
            //        else
            //        {
            //            model = wordbll.GetModel_Process(ewID);
            //            bool res1 = wordbll.Add_Word(model);
            //        }
            //    }
            //}
            #endregion

            //WorkThread_first_Crime bll = new WorkThread_first_Crime();
            //bll.CLdata();

            //System.Diagnostics.Process.Start("http://192.168.1.160:5720/main.aspx");

            //new UpdateData().Update();
            //string str = "被告人×××以非法占有为目的，在医院盗窃他人财物，其行为已构成盗窃罪。";
            //str = str.Substring(0, str.IndexOf("已构成"));
            //string str = "未按期归还贷款本金，从逾期之日起按约定的利率加收50‰的罚息利率计收罚息。";
            //string str1 = "计算逾期利息。";
            //int str1Len = str1.Length;
            //double same = Ledict.TextDiff.TextComparison.GetTextSameCharsCount(str, str1);
            //if (Math.Round(((double)same / str1Len), 2) >= 0.6)
            //{
            //    Console.WriteLine();
            //}
            //发布地址
            //            3、\\192.168.1.12\biaoshugongju\ 发布程序160版本对应的文件夹
            //4、http://192.168.1.12:8081/ 发布程序160版本对应的下载地址
            //            5、\\192.168.1.12\biaoshugongju67\ 发布程序67版本对应的文件夹
            //6、http://192.168.1.12:8082/ 发布程序67版本对应的下载地址

            //Log.WriteLog("表述工具启动");
            // string ss = DateTime.Now.ToString("yyyyMMddHHmmss");
            //string str = File.ReadAllText("D:\\1.txt");
            //for (int i = 0; i < 10; i++)
            //{
            //    MessageBox.Show(DateTime.Now.ToString("yyyyMMddHHmmssff") +" |"+ DateTime.Now.ToString("yyyyMMddHHmmssff").Length);
            //}
            // str = File.ReadAllText("D:\\1.docx");

            //string webapiUrl1 = "http://" + "192.168.1.52:10044" + "/system/config/v1/getfilecontent";
            //RequestContent rc = new RequestContent() { systemName = "Ldt_JudgeDocSystem", moudleName = "SYS_CaseCause\\ElementXML", fileType = "xml", fileName = "1655" };
            //ComResult model = WebUtil.DoPost<ComResult>(webapiUrl1, rc, "UTF-8");
            //if (model.result.code == "1")
            //{
            //    string str = model.body.content;
            //    rc.content = str;
            //    string weburl= "http://" + "192.168.1.52:10044" + "/system/config/v1/setfilecontent";
            //    ComResult model1 = WebUtil.DoPost<ComResult>(webapiUrl1, rc, "UTF-8");
            //    if (model.result.code == "1")
            //    {

            //    }
            //    }
            //string message = "";
            //AnalysisArgumentFocus.AnalysisMain analysisMain = new AnalysisArgumentFocus.AnalysisMain();
            //AnalysisArgumentFocus.AnalysisMain.CommonConnection = ConfigHelper.ConnectionStrings("LdtCommonManage").ConnectionString;
            //AnalysisArgumentFocus.AnalysisMain.SystemConnection = ConfigHelper.ConnectionStrings("JudgeDoc").ConnectionString;
            //Dictionary<string, string> listvalue = analysisMain.GetArgumentFocus("二被告应否承担还款责任。", "1670", "MSCourtRecord", "MS_CR_ArgumentFocus", out message);
            //if (message.Contains("成功"))
            //{
            //    if (listvalue.Count > 0)
            //    {
            //        foreach (var item in listvalue.Keys)
            //        {

            //        }
            //    }
            //}
            //依赖注入
            // AutofacRegister.RegisterMain();
            //TestIoc();
            //     string test = @" 送达回证";
            //RegexParse.RegexParse getregex = new RegexParse.RegexParse();
            //var ParagraphText = getregex.IsMatch("EI1710171630011809", test);//排除金额，多×××
            //ParagraphText = getregex.GetParseValue("dsrdl", ParagraphText);
            //ParagraphText = getregex.GetParseValue("wbxxpc", ParagraphText);
            //RequestWord rc = new RequestWord() { content = ParagraphText.Trim(), caseCauseCode = "2319", industryCode = "通用", isSegment = "是" };
            //string weburl = "http://192.168.1.160:15008/lexicon/api/v1/words/";
            //WordResult model = WebUtil.DoPost<WordResult>(weburl, rc, 100);
            //if (model.result.code == "1")
            //{
            //    List<thesaurusModel> sts = model.body;
            //}
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //全局异常捕捉
            Application.ThreadException += Application_ThreadException; //UI线程异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //CefSettings settings = new CefSettings();
            //settings.IgnoreCertificateErrors = true;
            //settings.Locale = "zh-CN";
            //settings.CachePath = AppDomain.CurrentDomain.BaseDirectory + "/Cache";
            //Cef.Initialize(settings);

            //多线程异常
            //string desc = "本院依照《中华人民共和国合同法》第二百零五条、第二百零六条、第二百零七条，《中华人民共和国物权法》第一百七十三条、第一百七十六条、第一百九十五条第一条、第二款、第二百零三条第一款，《中华人民共和国担保法》第十八条、第二十一条、第三十一条，《最高人民法院关于审理涉及夫妻债务纠纷案件适用法律有关问题的解释》第一条、第三条及《中华人民共和国民事诉讼法》第一百四十四条的规定，判决如下：";
            //string desc = "中华人民共和国合同法中华人民共和国合同法";
            //RegexParse.RegexParse getregex = new RegexParse.RegexParse();
            //var test = getregex.GetParseValue("EI2109261702590001", desc);
            //var test1 = getregex.GetParseValue("EI2109261647580001", desc);
            //var matchschild1 = getregex.IsMatch("EI2109261702590001", desc);
            //var matchschild2 = getregex.IsMatch("EI2109261647580001", desc);
            //var matchschild3 = getregex.IsMatch("dwxmzcc", desc);
            //var matchschild4 = getregex.IsMatch("zrrzcd", desc);


            #region 删除引用法规表中条款 项相同的数据取一条
            //DataTable dt = new TreeDateDAL().GetCaseProperty1();
            //StringBuilder sb = new StringBuilder();
            //foreach (DataRow dr in dt.Rows)
            //{
            //    string OLR_SituationID = dr["OLR_SituationID"].ToString();
            //    string OLR_Law_ProvID = dr["OLR_Law_ProvID"].ToString();
            //    string OLR_LawID = dr["OLR_LawID"].ToString();
            //    string OLR_CaseCauseID = dr["OLR_CaseCauseID"].ToString();
            //    string OLR_Law_ClauseNumber = dr["OLR_Law_ClauseNumber"].ToString();
            //    string OLR_Law_ItemNumber = dr["OLR_Law_ItemNumber"].ToString();
            //    DataTable dt1 = new TreeDateDAL().GetCaseProperty2(OLR_SituationID, OLR_Law_ProvID, OLR_LawID, OLR_CaseCauseID, OLR_Law_ClauseNumber, OLR_Law_ItemNumber);
            //    if (dt1 != null && dt1.Rows.Count > 0)
            //    {
            //        sb.Clear();
            //        sb.Append(" delete from SYS_QuoteLawRel where QLR_ID in( ");
            //        for (int i = 0; i < dt1.Rows.Count; i++)
            //        {
            //            if (i == 0)
            //            {
            //                continue;
            //            }
            //            else
            //            {
            //                sb.Append("'" + dt1.Rows[i]["QLR_ID"].ToString() + "',");
            //            }
            //        }
            //        sb.Append(" '' )");
            //        bool res = new TreeDateDAL().ConvertModeDeleteConfig(sb.ToString());
            //    }
            //}
            #endregion
            //public DataTable GetCaseProperty2(string OLR_SituationID, string OLR_Law_ProvID, string OLR_LawID, string OLR_CaseCauseID, string OLR_Law_ClauseNumber, string OLR_Law_ItemNumber)

            #region 检察院情形情节表述添加工具需求
            //string[] names = new string[] { "构成", "其行为已构成", "其行为均已构成", "其行为已经构成", "被告人的行为已构成", "公诉机关指控的事实与罪名成立", "人民检察院指控", "本院不予采纳", "不构成", "因此本案性质应当认定为" };
            ////string[] names = new string[] {"其行为已构成" };
            //foreach (string name in names)
            //{
            //    NewIDBLL newid = new NewIDBLL();
            //    Express_WordDAL dal = new Express_WordDAL();
            //    DataTable dt = dal.GetExpressWordData(name);
            //    if (dt != null && dt.Rows.Count > 0)
            //    {
            //        foreach (DataRow dr in dt.Rows)
            //        {
            //            DataTable dt1 = dal.GetExpressWordData1(dr["MS_ID"].ToString(), name);
            //            if (dt1 != null && dt1.Rows.Count > 0)
            //            {
            //                DataTable dt2 = dal.GetMSID(dt1.Rows[0]["MS_ID"].ToString());
            //                SYS_Express_Word model = new SYS_Express_Word();

            //                if (dt2 != null && dt2.Rows.Count > 0)
            //                {


            //                    int userCount = Convert.ToInt32(dt2.Rows[0]["EW_UseCount"].ToString());
            //                    if (Convert.ToInt32(dt1.Rows[0]["EW_UseCount"].ToString()) > userCount)
            //                    {
            //                        string ewid = dt2.Rows[0]["EW_ID"].ToString();
            //                        if (dal.DeleteEwID(ewid))
            //                        {
            //                            model.MS_ID = dt1.Rows[0]["MS_ID"].ToString();
            //                            model.EW_WordCount = Convert.ToInt32(dt1.Rows[0]["EW_WordCount"].ToString());
            //                            model.EW_UseCount = Convert.ToInt32(dt1.Rows[0]["EW_UseCount"].ToString());
            //                            model.EW_CaseId = dt1.Rows[0]["EW_CaseId"].ToString();
            //                            model.ParagraphTypeId = Convert.ToInt32(dt1.Rows[0]["ParagraphTypeId"].ToString());
            //                            model.EW_WordPurpose = 3;
            //                            model.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
            //                            model.EW_Content = dt1.Rows[0]["EW_Content"].ToString();
            //                            if (model.EW_Content != null)
            //                            {
            //                                model.EW_Content = model.EW_Content.Substring(0, model.EW_Content.IndexOf(name)) + "。";
            //                                dal.Add_Word(model);//添加word 表
            //                            }
            //                        }
            //                    }
            //                }
            //                else
            //                {
            //                    model.MS_ID = dt1.Rows[0]["MS_ID"].ToString();
            //                    model.EW_WordCount = Convert.ToInt32(dt1.Rows[0]["EW_WordCount"].ToString());
            //                    model.EW_UseCount = Convert.ToInt32(dt1.Rows[0]["EW_UseCount"].ToString());
            //                    model.EW_CaseId = dt1.Rows[0]["EW_CaseId"].ToString();
            //                    model.ParagraphTypeId = Convert.ToInt32(dt1.Rows[0]["ParagraphTypeId"].ToString());
            //                    model.EW_WordPurpose = 3;
            //                    model.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
            //                    model.EW_Content = dt1.Rows[0]["EW_Content"].ToString();
            //                    if (model.EW_Content != null)
            //                    {
            //                        model.EW_Content = model.EW_Content.Substring(0, model.EW_Content.IndexOf(name)) + "。";
            //                        dal.Add_Word(model);//添加word 表
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            #endregion

            #region 判断进程中是否已存在
            //var p = Process.GetCurrentProcess().ProcessName;
            //var processes = Process.GetProcessesByName(p);
            //if (processes.Length > 1)
            //{
            //    MessageBox.Show("程序已经在运行中", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    Application.Exit();
            //}
            //elseIrisSkin4
            //{
            // Application.Run(new Form1());
            //Application.Run(new TestForm());
            //} 
            #endregion

            //TestForm tf = new TestForm();
            //tf.ShowDialog();
            //return;
            //BLL.WorkProcess.WorkThread_Public work = new BLL.WorkProcess.WorkThread_Public();
            //work.AddMatch_virtual("SCC1608080932060003", "单一");
            //work.AddMatch_virtual("MCC1608080932060003", "组合");

            //Application.Run(new MainForm());

            //打开登录窗体成功后打开主界面

            //Application.Run(new Form2());

            var frmLogin = new Frm.FrmLogin();
            frmLogin.ShowDialog();
            if (frmLogin.DialogResult == DialogResult.OK)
            {
                Application.Run(new MainForm());
                Log.WriteLog("登录成功");
            }
        }

        #region UI线程异常与多线程异常
        /// <summary>
        ///UI线程异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            FrmBugReport.ShowBug(e.Exception);
        }

        /// <summary>
        ///多线程异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            FrmBugReport.ShowBug((Exception)e.ExceptionObject);
        }
        #endregion

        //public static bool TestProgram(string ip, string port)
        //{
        //    try
        //    {
        //        HttpHelper.Get($"http://{ip}:{port}", null, 5000);
        //        return true;
        //    }
        //    catch (Exception)
        //    {
        //        //只捕捉超时错误
        //        return false;
        //    }
        //}

        #region 测试IOC
        /// <summary>
        ///     测试IOC
        /// </summary>
        //private static void TestIoc()
        //{
        //    var getter = ServiceLocator.Current.GetInstance<IServiceGetter>();
        //    var testManager = getter.Get<ITestManager>();
        //    //testManager.GetTreeData();
        //}

        #endregion

        #region 拷贝类（未用）
        public static object Copy(this object obj)
        {
            Object targetDeepCopyObj;
            Type targetType = obj.GetType();
            //值类型  
            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            //引用类型   
            else
            {
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象   
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }

                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                            }
                        }

                    }
                }
            }
            return targetDeepCopyObj;
        } 
        #endregion

    }
}